<template>
  <div class="container">
    <el-divider>评论({{ total }})</el-divider>
    <div class="topDis">
      <div v-if="isLogin" class="reply" style="border: none;">
        <transition>
          <div class="input-wrapper" style="border: 1px solid rgba(229, 231, 235, 1);">
            <el-input
              v-if="isEdit0"
              v-model="inputComment0"
              :autosize="{ minRows: 2, maxRows: 5}"
              placeholder="请发表有价值的评论， 评论不欢迎灌水，良好的社区氛围需大家一起维护。"
              class="gray-bg-input"
              type="textarea"
              autofocus/>
            <markdown-viewer v-else v-model="inputComment0" class="md-view" height="800px"/>
            <div class="tool-control">
              <div class="left-control">
                <el-button v-if="isEdit0" icon="el-icon-link" class="codeBtn" size="small" @click="insertLink0">插入链接
                </el-button>
                <el-select
                  v-if="isEdit0"
                  v-model="lanName0"
                  class="codeSelect"
                  placeholder="插入代码"
                  size="small"
                  @change="insertCode0">
                  <el-option
                    v-for="lan in lans"
                    :key="lan"
                    :label="lan"
                    :value="lan"/>
                </el-select>
              </div>
              <div class="right-control">
                <el-button class="btn" type="primary" round @click="isEdit0 = !isEdit0">{{ isEdit0 ? '预览' : '编辑' }}
                </el-button>
                <el-button :disabled="saveBtnDisabled0" class="btn" type="success" round @click="commitComment0">评论
                </el-button>
              </div>
            </div>
          </div>
        </transition>
      </div>

      <div v-else class="topDis_c">
        请先&nbsp;
        <el-button type="primary" size="mini" @click="toLogin">登录</el-button>
        &nbsp;后发表评论
      </div>
    </div>

    <div
      v-for="item in comments"
      :key="item.id"
      class="comment">

      <div class="info">
        <router-link :to="'/ucenter/' + item.userId">
          <el-avatar :src="item.userAvatar" size="medium"/>
        </router-link>
        <div class="right">
          <router-link :to="'/ucenter/' + item.userId">
            <div class="name">{{ item.userNickName }}</div>
          </router-link>
          <div class="date">{{ formatTime(item.publishDate) }}</div>
        </div>
      </div>

      <div class="content">
        <markdown-viewer v-model="item.content" height="800px"/>
        <span class="comment-reply" @click="showCommentInput(item.id, item)">
          <i class="el-icon-s-comment"/><span>回复</span>
        </span>
        <span class="comment-reply" @click="report(item.id)">
          <i class="el-icon-warning"/><span>举报</span>
        </span>
      </div>

      <div class="reply">

        <div v-for="reply in item.reply" :key="reply.id" class="item">
          <div class="reply-content">
            <router-link :to="'/ucenter/' + reply.userId">
              <el-avatar :src="reply.userAvatar" size="small"/>
            </router-link>
            <router-link :to="'/ucenter/' + reply.userId">
              <span class="from-name">{{ reply.userNickName }}</span>
            </router-link>
            <span class="reply_to_reply">&nbsp; 回复</span>
            <router-link :to="'/ucenter/' + reply.toUserId">
              <span class="to-name">
                {{ reply.toUserNickName }}<span style="color: black">：</span>
              </span>
            </router-link>
            <markdown-viewer v-model="reply.content" height="800px"/>
          </div>
          <div class="reply-bottom">
            <span>{{ formatTime(reply.publishDate) }}</span>
            <span class="reply-text" @click="showCommentInput(item.id, reply)">
              <i class="el-icon-s-comment"/><span>回复</span>
            </span>
            <span class="reply-text" @click="report(reply.id)">
              <i class="el-icon-warning"/><span>举报</span>
            </span>
          </div>
        </div>

        <transition name="reply">
          <div v-if="currentCommentId === item.id" class="input-wrapper">
            <el-input
              v-if="isEdit"
              ref="reply"
              v-model="inputComment"
              :autosize="{ minRows: 2, maxRows: 5}"
              :placeholder="placeholder"
              class="gray-bg-input"
              type="textarea"
              autofocus/>
            <markdown-viewer v-else v-model="inputComment" class="md-view" height="800px"/>
            <div class="tool-control">
              <div class="left-control">
                <el-button v-if="isEdit" icon="el-icon-link" class="codeBtn" size="small" @click="insertLink">插入链接
                </el-button>
                <el-select
                  v-if="isEdit"
                  v-model="lanName"
                  class="codeSelect"
                  placeholder="插入代码"
                  size="small"
                  @change="insertCode">
                  <el-option
                    v-for="lan in lans"
                    :key="lan"
                    :label="lan"
                    :value="lan"/>
                </el-select>
              </div>
              <div class="right-control">
                <el-button round @click="cancel">取消</el-button>
                <el-button class="btn" type="primary" round @click="isEdit = !isEdit">{{ isEdit ? '预览' : '编辑' }}
                </el-button>
                <el-button :disabled="saveBtnDisabled" class="btn" type="success" round @click="commitComment">评论
                </el-button>
              </div>
            </div>
          </div>
        </transition>
      </div>

    </div>

    <el-pagination
      :current-page="page"
      :total="total"
      style="padding: 30px 0; text-align: center;"
      layout="prev, pager, next, jumper, ->, total, slot"
      @current-change="changePage"/>

    <el-dialog :visible.sync="reportVisible" title="举报反馈" center>
      <el-input
        v-model="discussionReportRequest.reportReason"
        :rows="5"
        type="textarea"
        placeholder="请详细描述举报原因，我们将第一时间核实处理"
        maxlength="200"
        show-word-limit
      />
      <span slot="footer" class="dialog-footer">
        <el-button @click="reportVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitReport">提 交</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { mapGetters } from 'vuex'

import MarkdownViewer from '@/components/MarkdownViewer'

import discussionApi from '@/api/com/discussion'

export default {
  name: 'Comment',
  components: { MarkdownViewer },
  props: {
    belongId: {
      type: String,
      required: true
    }
  },
  data() {
    return {
      comments: [],
      inputComment0: '',
      inputComment: '',
      currentCommentId: '',
      placeholder: '请发表有价值的评论， 评论不欢迎灌水，良好的社区氛围需大家一起维护。',
      reportVisible: false,
      discussionReportRequest: {
        discussionId: '',
        reportReason: ''
      },
      lans: ['C', 'C++', 'Java', 'Python'],
      lanName0: '',
      lanName: '',
      isEdit0: true,
      isEdit: true,
      saveBtnDisabled0: false,
      saveBtnDisabled: false,
      discussionAddRequest0: {
        parentId: '',
        content: ''
      },
      discussionAddRequest: {
        parentId: '',
        replyToUserId: '',
        replyToUserNickname: '',
        content: ''
      },
      page: 1,
      total: 0,
      discussionPageRequest: {
        page: 1,
        limit: 5,
        ownerId: ''
      },
      loading: false,
      noMore: false
    }
  },
  computed: {
    ...mapGetters([
      'roles'
    ]),

    isLogin() {
      return this.roles && this.roles.length > 0
    },

    isDisabled() {
      return this.loading || this.noMore
    }

  },
  created() {
    this.discussionPageRequest.ownerId = this.belongId

    this.getDiscussionList()
  },
  methods: {

    getDiscussionList() {
      this.discussionPageRequest.page = this.page
      discussionApi.getDiscussionList(this.discussionPageRequest).then(res => {
        this.total = Number.parseInt(res.result.counts)
        this.comments = res.result.items
        this.noMore = res.result.length < this.discussionPageRequest.limit
      }).catch(error => {
        console.log(error)
      })
    },

    /**
     * 点击评论按钮显示输入框
     * @param commentId
     * @param comment 当前回复消息
     */
    showCommentInput(commentId, comment) {
      if (!this.isLogin) {
        this.$message({
          offset: 50,
          type: 'warning',
          message: '请先登录'
        })
        this.toLogin()
      }
      this.isEdit = true
      const replyUserId = comment.userId
      const replyUserNickName = comment.userNickName
      this.inputComment = ''
      this.placeholder = '回复：' + replyUserNickName
      this.currentCommentId = commentId

      this.discussionAddRequest.parentId = commentId
      this.discussionAddRequest.replyToUserId = replyUserId
      this.discussionAddRequest.replyToUserNickname = replyUserNickName

      this.$nextTick(() => {
        console.log(this.$refs.reply)
        this.$refs.reply[0].focus()
      })
    },

    /**
     * 点击取消按钮
     */
    cancel() {
      this.currentCommentId = ''
      this.isEdit = true

      this.discussionAddRequest.parentId = ''
      this.discussionAddRequest.replyToUserId = ''
      this.discussionAddRequest.replyToUserNickname = ''
    },

    /**
     * 提交评论
     */
    commitComment0() {
      this.discussionAddRequest0.parentId = this.belongId
      this.discussionAddRequest0.content = this.inputComment0
      this.saveBtnDisabled0 = true
      discussionApi.createDiscuss(this.discussionAddRequest0).then(res => {
        this.$message({
          offset: 50,
          type: 'success',
          message: '评论成功'
        })
        this.total += 1
        this.comments.unshift(res.result)
        this.inputComment0 = ''
        this.saveBtnDisabled0 = false
      }).catch(error => {
        this.saveBtnDisabled0 = false
        console.log(error)
      })
    },

    /**
     * 提交评论
     */
    commitComment() {
      this.discussionAddRequest.content = this.inputComment
      this.saveBtnDisabled = true
      discussionApi.createDiscuss(this.discussionAddRequest).then(res => {
        this.$message({
          offset: 50,
          type: 'success',
          message: '评论成功'
        })
        const poi = this.comments.findIndex(comment => comment.id === this.discussionAddRequest.parentId)
        this.comments[poi].reply.unshift(res.result)
        this.cancel()
        this.saveBtnDisabled = false
      }).catch(error => {
        this.saveBtnDisabled = false
        console.log(error)
      })
    },

    /**
     * 举报某个评论
     * @param id
     */
    report(id) {
      if (!this.isLogin) {
        this.$message({
          offset: 50,
          type: 'warning',
          message: '请先登录'
        })
        this.toLogin()
      }
      console.log(id)
      this.reportVisible = true
      this.discussionReportRequest.discussionId = id
    },

    submitReport() {
      discussionApi.reportDiscussion(this.discussionReportRequest).then(res => {
        this.$message({
          offset: 50,
          type: 'success',
          message: res.result
        })
        this.reportVisible = false
        this.discussionReportRequest.discussionId = ''
        this.discussionReportRequest.reportReason = ''
      }).catch(error => {
        console.log(error)
        this.reportVisible = false
        this.discussionReportRequest.discussionId = ''
        this.discussionReportRequest.reportReason = ''
      })
    },

    /**
     * 插入链接
     */
    insertLink0() {
      if (this.inputComment0 !== '') {
        this.inputComment0 += '\n'
      }
      this.inputComment0 += '[链接](http://zhzby.xyz/)'
    },

    /**
     * 插入链接
     */
    insertLink() {
      if (this.inputComment !== '') {
        this.inputComment += '\n'
      }
      this.inputComment += '[链接](http://zhzby.xyz/)'
    },

    /**
     * 插入代码片
     */
    insertCode0() {
      if (this.inputComment0 !== '') {
        this.inputComment0 += '\n'
      }
      if (this.lanName0 === 'Java') {
        this.inputComment0 += '```java\n' +
          '\n```'
      } else if (this.lanName0 === 'Python') {
        this.inputComment0 += '```python\n' +
          '\n```'
      } else {
        this.inputComment0 += '```c\n' +
          '\n```'
      }
      this.lanName0 = ''
    },

    /**
     * 插入代码片
     */
    insertCode() {
      if (this.inputComment !== '') {
        this.inputComment += '\n'
      }
      if (this.lanName === 'Java') {
        this.inputComment += '```java\n' +
          '\n```'
      } else if (this.lanName === 'Python') {
        this.inputComment += '```python\n' +
          '\n```'
      } else {
        this.inputComment += '```c\n' +
          '\n```'
      }
      this.lanName = ''
    },

    toLogin() {
      this.$router.push({ path: '/login?redirect=' + this.$route.path })
    },

    changePage(page) {
      this.page = page
      this.getDiscussionList()
    },

    formatTime(time) {
      const date = new Date(time)
      const today = new Date()
      const diff = (today.getTime() - date.getTime()) / 1000
      const dayDiff = Math.floor(diff / 86400)

      if (isNaN(dayDiff) || dayDiff < 0 || dayDiff > 7) {
        return time.substring(0, 10)
      }
      return (
        (dayDiff === 0 &&
          ((diff < 60 && '刚刚') ||
            (diff < 120 && '1分钟前') ||
            (diff < 3600 && Math.floor(diff / 60) + '分钟前') ||
            (diff < 7200 && '1小时前') ||
            (diff < 86400 && Math.floor(diff / 3600) + '小时前'))) ||
        (dayDiff === 1 && '昨天') ||
        (dayDiff <= 7 && dayDiff + '天前')
      )
    }

  }
}
</script>

<style scoped>
.container {
  padding: 0 20px;
  box-sizing: border-box;
}

.container .comment {
  display: flex;
  flex-direction: column;
  padding: 10px;
  border-bottom: 1px solid #F2F6FC;
}

.container .comment .info {
  display: flex;
  align-items: center;
}

.container .comment .info .right {
  display: flex;
  flex-direction: column;
  margin-left: 10px;
}

.container .comment .info .right .name {
  font-size: 16px;
  color: #303133;
  margin-bottom: 5px;
  font-weight: 500;
}

.container .comment .info .right .date {
  font-size: 12px;
  color: #909399;
}

.container .comment .content {
  font-size: 16px;
  color: #303133;
  line-height: 20px;
  padding: 10px 0;
}

.container .comment .comment-reply {
  color: #909399;
  align-items: center;
  cursor: pointer;
}

.container .comment .comment-reply:hover {
  color: #333;
}

.container .reply {
  margin: 10px 0;
  border-left: 2px solid #DCDFE6;
}

.container .reply .item {
  margin: 0 10px;
  padding: 10px 0;
  border-bottom: 1px dashed #EBEEF5;
}

.container .reply .item .reply-content {
  align-items: center;
  font-size: 14px;
  color: #303133;
}

.container .reply .item .reply-content .from-name {
  margin-left: 5px;
  color: #555666;
}

.container .reply .item .reply-content .from-name:hover, .container .reply .item .reply-content .to-name:hover, .container .comment .info .right .name:hover {
  color: #409EFF;
}

.container .reply .item .reply-content .reply_to_reply {
  color: #909399;
  font-size: 12px;
}

.container .reply .item .reply-content .to-name {
  color: #555666;
  margin-left: 5px;
  margin-right: 5px;
}

.container .reply .item .reply-bottom {
  display: flex;
  align-items: center;
  margin-top: 6px;
  font-size: 12px;
  color: #909399;
}

.container .reply .item .reply-bottom .reply-text {
  display: flex;
  align-items: center;
  margin-left: 10px;
  cursor: pointer;
}

.container .reply .item .reply-bottom .reply-text:hover {
  color: #333;
}

.container .reply .input-wrapper {
  padding: 10px;
  border: 1px solid rgba(229, 231, 235, 1);
  border-left: none;
}

.container .reply .input-wrapper .tool-control {
  display: flex;
  flex-flow: row nowrap;
  justify-content: space-between;
}

.container .reply .input-wrapper .tool-control .left-control {
  justify-content: flex-start;
  align-items: center;
  padding-top: 10px;
}

.container .reply .input-wrapper .tool-control .right-control {
  justify-content: flex-end;
  align-items: center;
  padding-top: 10px;
}

.container .reply .input-wrapper .tool-control .left-control /deep/ input::placeholder {
  color: #606266;
  font-size: 12px;
}

.codeBtn:hover, .codeBtn:focus {
  color: #606266;
  background-color: #FFF;
  border: 1px solid #c0c4cc;
}

.codeSelect {
  width: 100px;
}

.md-view {
  border-bottom: 1px solid rgba(229, 231, 235, 1);
}

.topDis {
  padding-top: 10px;
}

.topDis_c {
  text-align: center;
  height: 70px;
  border: 1px solid rgba(242, 243, 245, 1);
  border-radius: 3px;
  background: rgba(247, 248, 250, 1);
  display: flex;
  -webkit-box-pack: center;
  justify-content: center;
  -webkit-box-align: center;
  align-items: center;
  color: rgb(132, 139, 150, 1);
}

.el-divider .el-divider__text {
  color: rgb(132, 139, 150, 1);
}

</style>
